<!-- views/reconciliation/Results.vue -->
<template>
  <div class="reconciliation-results">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">对账结果</h1>
        <div class="status-badges">
          <el-tag type="success" class="matched-badge">
            <el-icon><SuccessFilled /></el-icon>
            已匹配: {{ stats.matchedCount }}
          </el-tag>
          <el-tag type="warning" class="pending-badge">
            <el-icon><Clock /></el-icon>
            待确认: {{ stats.pendingCount }}
          </el-tag>
          <el-tag type="danger" class="unmatched-badge">
            <el-icon><WarningFilled /></el-icon>
            未匹配: {{ stats.unmatchedCount }}
          </el-tag>
        </div>
      </div>
      
      <div class="header-actions">
        <!-- 智能分析报告 -->
        <el-button 
          type="primary" 
          :icon="TrendCharts" 
          @click="generateAnalysisReport"
          :loading="reportLoading"
        >
          智能分析报告
        </el-button>
        
        <!-- 批量操作 -->
        <el-button 
          :disabled="selectedMatches.length === 0" 
          :icon="Check" 
          @click="batchConfirmMatches"
        >
          批量确认 ({{ selectedMatches.length }})
        </el-button>
        <el-button 
          :disabled="selectedMatches.length === 0" 
          :icon="Close" 
          @click="batchRejectMatches"
          type="danger"
        >
          批量拒绝 ({{ selectedMatches.length }})
        </el-button>
        
        <!-- 导出对账结果 -->
        <el-button :icon="Download" @click="exportResults">
          导出结果
        </el-button>
        
        <!-- 重新对账 -->
        <el-button :icon="Refresh" @click="handleReReconciliation">
          重新对账
        </el-button>
      </div>
    </div>

    <!-- 统计概览卡片 -->
    <el-row :gutter="16" class="stats-cards">
      <el-col :span="6">
        <StatCard
          title="对账准确率"
          :value="stats.accuracyRate"
          suffix="%"
          type="success"
          icon="SuccessFilled"
          :trend="stats.accuracyTrend"
          :progress="stats.accuracyRate"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="智能匹配数"
          :value="stats.autoMatchedCount"
          type="primary"
          icon="MagicStick"
          :trend="stats.autoMatchTrend"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="平均置信度"
          :value="stats.avgConfidence"
          suffix="%"
          type="warning"
          icon="DataAnalysis"
          :trend="stats.confidenceTrend"
        />
      </el-col>
      <el-col :span="6">
        <StatCard
          title="对账效率"
          :value="stats.efficiencyScore"
          suffix="分"
          type="info"
          icon="Opportunity"
          :trend="stats.efficiencyTrend"
        />
      </el-col>
    </el-row>

    <!-- 对账结果筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="queryParams" inline>
        <el-form-item label="匹配状态">
          <el-select v-model="queryParams.matchStatus" clearable class="form-item-width">
            <el-option label="全部" value="" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="待确认" value="pending" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="自动匹配" value="auto" />
            <el-option label="手动匹配" value="manual" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="置信度范围">
          <el-slider
            v-model="queryParams.confidenceRange"
            range
            :min="0"
            :max="100"
            :step="5"
            show-stops
            style="width: 200px"
          />
          <span class="slider-values">
            {{ queryParams.confidenceRange[0] }}% - {{ queryParams.confidenceRange[1] }}%
          </span>
        </el-form-item>
        
        <el-form-item label="客户名称">
          <el-input
            v-model="queryParams.customerName"
            placeholder="输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="对账时间">
          <el-date-picker
            v-model="queryParams.reconciliationDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="金额差异">
          <el-input-number
            v-model="queryParams.maxAmountDiff"
            :min="0"
            :step="100"
            placeholder="最大金额差"
            style="width: 150px"
          >
            <template #append>元</template>
          </el-input-number>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            查询
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">
            重置
          </el-button>
          <el-button 
            link
            :icon="SetUp" 
            @click="showAdvancedFilter = !showAdvancedFilter"
          >
            高级筛选
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 高级筛选 -->
      <el-collapse-transition>
        <div v-show="showAdvancedFilter" class="advanced-filter">
          <el-divider content-position="left">高级筛选</el-divider>
          <el-form :model="queryParams" inline>
            <el-form-item label="匹配算法">
              <el-select v-model="queryParams.algorithm" clearable class="form-item-width">
                <el-option label="精确匹配" value="exact" />
                <el-option label="金额优先" value="amount_first" />
                <el-option label="时间窗口" value="time_window" />
                <el-option label="综合算法" value="comprehensive" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="操作人">
              <el-input
                v-model="queryParams.operator"
                placeholder="输入操作人姓名"
                clearable
                style="width: 150px"
              />
            </el-form-item>
            
            <el-form-item label="数据来源">
              <el-select v-model="queryParams.dataSource" clearable class="form-item-width">
                <el-option label="政采云API" value="zcy_api" />
                <el-option label="文件导入" value="file_import" />
                <el-option label="手工录入" value="manual" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="包含差异项">
              <el-switch v-model="queryParams.includeDifferences" />
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 对账结果标签页 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" type="card" @tab-click="handleTabChange">
        <!-- 全部结果 -->
        <el-tab-pane label="全部结果" name="all">
          <ResultsTable 
            :data="tableData"
            :loading="loading"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
            @confirm-match="handleConfirmMatch"
            @reject-match="handleRejectMatch"
            @view-details="showMatchDetails"
          />
        </el-tab-pane>
        
        <!-- 待确认 -->
        <el-tab-pane label="待确认" name="pending">
          <ResultsTable 
            :data="pendingData"
            :loading="loading"
            show-actions
            @selection-change="handleSelectionChange"
            @confirm-match="handleConfirmMatch"
            @reject-match="handleRejectMatch"
            @view-details="showMatchDetails"
          />
        </el-tab-pane>
        
        <!-- 高置信度 -->
        <el-tab-pane label="高置信度" name="high-confidence">
          <ResultsTable 
            :data="highConfidenceData"
            :loading="loading"
            @selection-change="handleSelectionChange"
            @confirm-match="handleConfirmMatch"
          />
        </el-tab-pane>
        
        <!-- 需人工核对 -->
        <el-tab-pane label="需人工核对" name="need-review">
          <ResultsTable 
            :data="needReviewData"
            :loading="loading"
            show-actions
            @selection-change="handleSelectionChange"
            @confirm-match="handleConfirmMatch"
            @reject-match="handleRejectMatch"
            @view-details="showMatchDetails"
          />
        </el-tab-pane>
        
        <!-- 匹配差异 -->
        <el-tab-pane label="匹配差异" name="differences">
          <DifferencesTable 
            :data="differencesData"
            :loading="loading"
            @resolve-difference="handleResolveDifference"
          />
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :total="total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 匹配详情抽屉 -->
    <MatchDetailsDrawer 
      v-model="detailsDrawerVisible"
      :match-data="currentMatch"
      @confirm="handleConfirmMatch"
      @reject="handleRejectMatch"
    />
    
    <!-- 报告对话框 -->
    <AnalysisReportDialog 
      v-model="reportDialogVisible"
      :data="reportData"
      @generate="handleGenerateReport"
    />
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useReconciliationStore } from '@/stores/reconciliationStore'
import { useAppStore } from '@/stores/appStore'
import { 
  Search, Refresh, Download, Operation, Filter, 
  Connection, Edit, More, CopyDocument, Delete, CircleCheck,
  OfficeBuilding, QuestionFilled, Check, SetUp, Coin, Timer,
  SuccessFilled, Clock, WarningFilled, TrendCharts, Close,
  MagicStick, DataAnalysis, Opportunity
} from '@element-plus/icons-vue'

// 组件导入
import ResultsTable from '@/components/reconciliation/ResultsTable.vue'
import MatchDetailsDrawer from '@/components/reconciliation/MatchDetailsDrawer.vue'
import StatCard from '@/components/StatCard.vue'
import DifferencesTable from '@/components/reconciliation/DifferencesTable.vue'
import AnalysisReportDialog from '@/components/reconciliation/AnalysisReportDialog.vue'

// API导入
import * as reconciliationAPI from '@/api/reconciliation'
// console.log('reconciliationAPI:', reconciliationAPI) // 调试用
import { useRouter } from 'vue-router'

// Store
const reconciliationStore = useReconciliationStore()
const router = useRouter()

// 类型定义
interface OrderInfo {
  platformOrderId: string
  customerName: string
  orderAmount: number
  orderDate: string
  invoiceStatus: string
}

interface TransactionInfo {
  transactionId: string
  payerName: string
  transactionAmount: number
  transactionDate: string
  bankName: string
}

interface MatchInfo {
  matchType: string
  matchAlgorithm: string
  confidence: number
  matchStatus: string
  matchedBy: string
  matchedAt: string
  confirmedBy: string
  confirmedAt: string
}

interface DifferenceInfo {
  amountDiff: number
  dateDiff: number
  nameSimilarity: number
  hasDifferences: boolean
  differenceType: string
}

interface Reasoning {
  confidence: number
  factors: string[]
}

interface ReconciliationResult {
  id: string
  orderInfo: OrderInfo
  transactionInfo: TransactionInfo
  matchInfo: MatchInfo
  differenceInfo: DifferenceInfo
  reasoning: Reasoning
}

interface ReconciliationQueryParams {
  page: number
  limit: number
  matchStatus: string
  confidenceRange: number[]
  customerName: string
  reconciliationDateRange: string[]
  maxAmountDiff?: number
  algorithm: string
  operator: string
  dataSource: string
  includeDifferences: boolean
}

interface ReconciliationStats {
  matchedCount: number
  pendingCount: number
  unmatchedCount: number
  accuracyRate: number
  autoMatchedCount: number
  avgConfidence: number
  efficiencyScore: number
  accuracyTrend: number
  autoMatchTrend: number
  confidenceTrend: number
  efficiencyTrend: number
}

// 设置页面标题
const appStore = useAppStore();

// 响应式数据
const loading = ref(false);
const tableData = ref<ReconciliationResult[]>([]);
const selectedMatches = ref<ReconciliationResult[]>([]);
const total = ref(0);

const activeTab = ref('all');
const showAdvancedFilter = ref(false);
const detailsDrawerVisible = ref(false);
const reportLoading = ref(false);
const reportDialogVisible = ref(false);
const reportData = ref(null);

const currentMatch = ref<ReconciliationResult | null>(null);

// 查询参数
const queryParams = reactive<ReconciliationQueryParams>({
  page: 1,
  limit: 20,
  matchStatus: '',
  confidenceRange: [80, 100],
  customerName: '',
  reconciliationDateRange: [],
  maxAmountDiff: undefined,
  algorithm: '',
  operator: '',
  dataSource: '',
  includeDifferences: false
});

// 统计信息 (暂时使用模拟数据)
const stats = reactive<ReconciliationStats>({
  matchedCount: 1250,
  pendingCount: 89,
  unmatchedCount: 42,
  accuracyRate: 96.8,
  autoMatchedCount: 1120,
  avgConfidence: 87.5,
  efficiencyScore: 92,
  accuracyTrend: 2.3,
  autoMatchTrend: 5.1,
  confidenceTrend: 1.8,
  efficiencyTrend: 3.2
});

// 计算属性
const pendingData = computed(() => 
  tableData.value.filter((item: ReconciliationResult) => item.matchInfo.matchStatus === 'pending')
);

const highConfidenceData = computed(() =>
  tableData.value.filter((item: ReconciliationResult) => item.matchInfo.confidence >= 80)
);

const needReviewData = computed(() =>
  tableData.value.filter((item: ReconciliationResult) => item.matchInfo.confidence < 80 && item.matchInfo.confidence >= 50)
);

const differencesData = computed(() =>
  tableData.value.filter((item: ReconciliationResult) => item.differenceInfo?.hasDifferences)
);

// 方法
const loadReconciliationResults = async () => {
  loading.value = true;
  try {
    // 调用真实的API
    console.log('reconciliationAPI:', reconciliationAPI); // 调试用
    const response: any = await reconciliationAPI.reconciliationAPI.getReconciliationResults({
      page: queryParams.page,
      limit: queryParams.limit,
      matchStatus: queryParams.matchStatus,
      confidenceRange: queryParams.confidenceRange,
      customerName: queryParams.customerName,
      reconciliationDateRange: queryParams.reconciliationDateRange,
      maxAmountDiff: queryParams.maxAmountDiff,
      algorithm: queryParams.algorithm,
      operator: queryParams.operator,
      dataSource: queryParams.dataSource,
      includeDifferences: queryParams.includeDifferences
    });
    
    // 检查响应数据是否存在
    if (!response) {
      console.error('API响应数据为空:', response);
      ElMessage.error('加载对账结果失败: 服务器响应数据为空');
      return;
    }
    
    // 直接使用API返回的已转换数据
    tableData.value = response.data.list;
    total.value = response.data.pagination?.total || 0;
  } catch (error: any) {
    console.error('加载对账结果失败:', error);
    ElMessage.error('加载对账结果失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  queryParams.page = 1;
  loadReconciliationResults();
};

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    limit: 20,
    matchStatus: '',
    confidenceRange: [80, 100],
    customerName: '',
    reconciliationDateRange: [],
    maxAmountDiff: undefined,
    algorithm: '',
    operator: '',
    dataSource: '',
    includeDifferences: false
  });
  loadReconciliationResults();
};

const handleTabChange = (tab: any) => {
  console.log('切换标签:', tab.props.name);
  // 可以根据标签加载不同的数据
};

const handleSelectionChange = (selection: ReconciliationResult[]) => {
  selectedMatches.value = selection;
};

const handleRowClick = (row: ReconciliationResult) => {
  currentMatch.value = row;
  detailsDrawerVisible.value = true;
};

const handleConfirmMatch = async (match: ReconciliationResult) => {
  try {
    await reconciliationAPI.reconciliationAPI.confirmMatch(match.id);
    ElMessage.success('确认匹配成功');
    loadReconciliationResults();
  } catch (error) {
    ElMessage.error('确认匹配失败: ' + (error as Error).message);
  }
};

const handleRejectMatch = async (match: ReconciliationResult) => {
  try {
    await reconciliationAPI.reconciliationAPI.rejectMatch(match.id);
    ElMessage.success('拒绝匹配成功');
    loadReconciliationResults();
  } catch (error) {
    ElMessage.error('拒绝匹配失败: ' + (error as Error).message);
  }
};

const batchConfirmMatches = async () => {
  if (selectedMatches.value.length === 0) return;
  
  try {
    // 批量确认每个匹配
    for (const match of selectedMatches.value) {
      await reconciliationAPI.reconciliationAPI.confirmMatch(match.id);
    }
    
    ElMessage.success(`批量确认 ${selectedMatches.value.length} 条匹配成功`);
    selectedMatches.value = [];
    loadReconciliationResults();
  } catch (error) {
    ElMessage.error('批量确认失败: ' + (error as Error).message);
  }
};

const batchRejectMatches = async () => {
  if (selectedMatches.value.length === 0) return;
  
  try {
    // 批量拒绝每个匹配
    for (const match of selectedMatches.value) {
      await reconciliationAPI.reconciliationAPI.rejectMatch(match.id);
    }
    
    ElMessage.success(`批量拒绝 ${selectedMatches.value.length} 条匹配成功`);
    selectedMatches.value = [];
    loadReconciliationResults();
  } catch (error) {
    ElMessage.error('批量拒绝失败: ' + (error as Error).message);
  }
};

const showMatchDetails = (match: ReconciliationResult) => {
  currentMatch.value = match;
  detailsDrawerVisible.value = true;
};

const generateAnalysisReport = async () => {
  reportLoading.value = true;
  reportDialogVisible.value = true;
  
  try {
    // 调用后端API生成分析报告
    const response = await reconciliationAPI.reconciliationAPI.generateAnalysisReport({
      // 可以传递当前的查询参数作为筛选条件
      ...queryParams
    });
    
    reportData.value = response.data;
    ElMessage.success('智能分析报告生成成功');
  } catch (error) {
    ElMessage.error('生成分析报告失败: ' + (error as Error).message);
    reportDialogVisible.value = false;
  } finally {
    reportLoading.value = false;
  }
};

// 添加报告对话框的事件处理方法
const handleGenerateReport = async (params?: any) => {
  reportLoading.value = true;
  
  try {
    // 调用后端API生成分析报告
    const response = await reconciliationAPI.reconciliationAPI.generateAnalysisReport(params || {
      // 可以传递当前的查询参数作为筛选条件
      ...queryParams
    });
    
    reportData.value = response.data;
    ElMessage.success('智能分析报告生成成功');
  } catch (error) {
    ElMessage.error('生成分析报告失败: ' + (error as Error).message);
  } finally {
    reportLoading.value = false;
  }
};

const exportResults = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    ElMessage.success('导出成功，请查看下载列表');
  } catch (error) {
    ElMessage.error('导出失败: ' + (error as Error).message);
  }
};

const handleReReconciliation = async () => {
  // 如果有选中的记录，则只重新对账选中的记录
  if (selectedMatches.value.length > 0) {
    try {
      // 弹出确认对话框
      await ElMessageBox.confirm(
        `确定要重新对账选中的 ${selectedMatches.value.length} 条记录吗？这将取消它们的确认状态并重新进入待匹配状态。`,
        '确认重新对账',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      const matchIds = selectedMatches.value.map((match: ReconciliationResult) => parseInt(match.id));
      await reconciliationAPI.reconciliationAPI.reReconcile(matchIds);
      ElMessage.success('重新对账成功');
      loadReconciliationResults();
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error('重新对账失败: ' + (error.message || '未知错误'));
      }
    }
  } else {
    // 重新对账所有已确认的匹配
    try {
      await ElMessageBox.confirm(
        '确定要重新对账所有已确认的匹配记录吗？这将取消所有已确认匹配的状态并重新进入待匹配状态。',
        '确认重新对账',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      await reconciliationAPI.reconciliationAPI.reReconcile();
      ElMessage.success('重新对账成功');
      loadReconciliationResults();
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error('重新对账失败: ' + (error.message || '未知错误'));
      }
    }
  }
};

const handleResolveDifference = (difference: any) => {
  console.log('解决差异:', difference);
  ElMessage.info('差异解决功能待实现');
};

const handleSizeChange = (size: number) => {
  queryParams.limit = size;
  queryParams.page = 1;
  loadReconciliationResults();
};

const handleCurrentChange = (page: number) => {
  queryParams.page = page;
  loadReconciliationResults();
};

// 生命周期
onMounted(() => {
  loadReconciliationResults();
});

</script>

<style scoped lang="scss">
.reconciliation-results {
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .header-left {
      .page-title {
        margin: 0 0 12px 0;
        font-size: 24px;
        font-weight: 600;
        color: #1f2d3d;
      }
      
      .status-badges {
        display: flex;
        gap: 12px;
        
        .el-tag {
          display: flex;
          align-items: center;
          gap: 4px;
          font-weight: 500;
          
          &.matched-badge {
            animation: pulse-success 2s infinite;
          }
          
          &.pending-badge {
            animation: pulse-warning 2s infinite;
          }
          
          &.unmatched-badge {
            animation: pulse-danger 2s infinite;
          }
        }
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .stats-cards {
    margin-bottom: 20px;
  }
  
  .filter-card {
    margin-bottom: 20px;
    
    .slider-values {
      margin-left: 12px;
      color: #606266;
      font-size: 14px;
      min-width: 100px;
      display: inline-block;
    }
    
    .advanced-filter {
      margin-top: 16px;
      
      .el-divider {
        margin: 16px 0;
      }
    }
  }
  
  .tabs-card {
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }
    
    :deep(.el-tabs__content) {
      padding: 0;
    }
    
    .pagination-container {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      padding: 16px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

@keyframes pulse-success {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; box-shadow: 0 0 8px rgba(82, 196, 26, 0.4); }
}

@keyframes pulse-warning {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; box-shadow: 0 0 8px rgba(250, 140, 22, 0.4); }
}

@keyframes pulse-danger {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; box-shadow: 0 0 8px rgba(245, 34, 45, 0.4); }
}
</style>